package com.mogist.hqc.module.product.ui

import android.app.Dialog
import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.net.Uri
import android.provider.MediaStore
import android.support.design.widget.TabLayout
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.MotionEvent
import android.view.View
import android.view.WindowManager
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import butterknife.OnClick
import butterknife.Optional
import cn.jzvd.Jzvd
import com.allure.lbanners.LMBanners
import com.allure.lbanners.adapter.LBaseAdapter
import com.bumptech.glide.Glide
import com.bumptech.glide.request.RequestOptions
import com.mogist.hqc.R
import com.mogist.hqc.base.BaseMVPActivity
import com.mogist.hqc.entitys.BaseModel
import com.mogist.hqc.entitys.response.CommentListVo
import com.mogist.hqc.entitys.response.ProductDetailItemVo
import com.mogist.hqc.entitys.response.ProductDetailVo
import com.mogist.hqc.module.common.ui.CommentListActivity
import com.mogist.hqc.module.product.adapter.ProductDayAdapter
import com.mogist.hqc.module.product.adapter.ProductDetailAdapter
import com.mogist.hqc.module.product.contract.ProductDetailContract
import com.mogist.hqc.module.product.presenter.ProductDetailPresenter
import com.mogist.hqc.mvp.HttpDto
import com.mogist.hqc.util.Constant
import com.mogist.hqc.util.Util
import com.mogist.hqc.view.CircleImageView
import com.mogist.hqc.view.PlayImageView
import com.mogist.hqc.view.TabLayoutAddOnClickHelper
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.activity_product_detail.*
import kotlinx.android.synthetic.main.include_title.*
import org.jetbrains.anko.contentView
import talex.zsw.basecore.util.*
import talex.zsw.basecore.util.glide.GlideApp
import talex.zsw.basecore.util.glide.GlideTool
import talex.zsw.basecore.view.other.RxToast
import talex.zsw.basecore.view.recyleview.DividerItemDecoration
import talex.zsw.basecore.view.recyleview.FullyLinearLayoutManager

/**
 * 作用：订单列表 - 详情
 * 作者：赵小白 email:vvtale@gmail.com  
 * 修改人：
 * 修改时间：
 * 修改备注：
 */
class ProductDetailActivity : BaseMVPActivity<ProductDetailContract.Presenter>(), ProductDetailContract.View, TabLayout.OnTabSelectedListener
{
    private var id = ""
    override fun initArgs(intent: Intent)
    {
        intent.getStringExtra("id")
                ?.let {
                    id = it
                }
    }

    override fun initView()
    {
        setContentView(R.layout.activity_product_detail)
        mPresenter = ProductDetailPresenter(this)
    }

    override fun initData()
    {
        initHeadView()
        initRecyclerView()
        initTab()
        getData(false)

        mTitleBar.setTitle("产品详情")
        //        mTitleBar.setRightIV2(R.drawable.i_more) {
        //        }
        mTitleBar.setRightIV(R.drawable.i_share) {
            // 产品分享
            showShareDialog(Util.createScreenShotBitmap(this@ProductDetailActivity,
                                                        BitmapTool.view2Bitmap(contentView)))
        }
    }

    @Optional
    @OnClick(R.id.mTvCall,
             R.id.mLLComment,
             R.id.mTvConsult,
             R.id.mTvCollect,
             R.id.mTvSure,
             R.id.mIvVideoClose)
    fun onViewClicked(view: View)
    {
        if (!isFastClick)
        {
            when (view.id)
            {
                R.id.mTvCall       ->
                { // 打电话
                    start(IntentTool.getDialIntent(Constant.TEL))
                }
                R.id.mTvConsult    ->
                { // 咨询
                    if (isLogin)
                    {
                        val intent = Intent(this@ProductDetailActivity, ConsultActivity::class.java)
                        intent.putExtra("id", id)
                        start(intent)
                    }
                }
                R.id.mTvCollect    ->
                { // 收藏
                    if (isLogin)
                    {
                        //type:COL收藏 NOCOL取消收藏 colType:PLACE地点ROUTE线路PRODUCT产品
                        val body = BaseModel(true)
                        body.type = "COL"
                        body.colType = "PRODUCT"
                        body.pdtId = id
                        mPresenter.getData(HttpDto(Constant.COLLECT_ADD, body, true).setShowError(
                                false))
                    }
                }
                R.id.mTvSure       ->
                { // 报名
                    choose()
                }
                R.id.mIvVideoClose ->
                { // 关闭视频区域
                    mJzvdStd.mediaInterface?.pause()
                    mJzvdStd.onStatePause()
                    mRLVideo.visibility = View.GONE
                    mIvVideoClose.visibility = View.GONE
                }
            }
        }
    }

    private fun choose()
    {
        if (detail == null)
        {
            getData(false)
        }
        else
        {
            if (detail!!.productProList == null || detail!!.productProList.isEmpty())
            {
                RxToast.error("该产品暂时无法购买")
            }
            else
            {
                if (isLogin)
                {
                    val intent =
                            Intent(this@ProductDetailActivity, ProductChooseActivity::class.java)
                    intent.putExtra("detail", detail)
                    start(intent)
                }
            }
        }
    }

    override fun onPause()
    {
        super.onPause()
        Jzvd.releaseAllVideos()
        mLMBanners?.stopImageTimerTask()
    }

    override fun onBackPressed()
    {
        if (mRLVideo.visibility == View.VISIBLE)
        {
            mJzvdStd.mediaInterface?.pause()
            mJzvdStd.onStatePause()
            mRLVideo.visibility = View.GONE
            mIvVideoClose.visibility = View.GONE
            return
        }
        if (Jzvd.backPress())
        {
            return
        }
        super.onBackPressed()
    }

    private var headView: View? = null
    private var mLMBanners: LMBanners<ProductDetailVo.ProductPicListEntity>? = null
    private var mTvTitle: TextView? = null
    private var mLLTag: LinearLayout? = null
    private var mTvTag1: TextView? = null
    private var mTvTag2: TextView? = null
    private var mTvTag3: TextView? = null
    private var mTvPrice: TextView? = null
    private var mTvStart: TextView? = null
    private var mLLDate: LinearLayout? = null
    private var mRvDate: RecyclerView? = null
    private var mLLComment: LinearLayout? = null
    private var mIvCIcon: CircleImageView? = null
    private var mTvCName: TextView? = null
    private var mTvCTime: TextView? = null
    private var mTvComment: TextView? = null
    private var mTabInside: TabLayout? = null

    private fun initHeadView()
    {
        headView = layoutInflater.inflate(R.layout.head_product_detail, null)
        headView?.let {
            mLMBanners = it.findViewById(R.id.mLMBanners)
            mTvTitle = it.findViewById(R.id.mTvTitle)
            mLLTag = it.findViewById(R.id.mLLTag)
            mTvTag1 = it.findViewById(R.id.mTvTag1)
            mTvTag2 = it.findViewById(R.id.mTvTag2)
            mTvTag3 = it.findViewById(R.id.mTvTag3)
            mTvPrice = it.findViewById(R.id.mTvPrice)
            mTvStart = it.findViewById(R.id.mTvStart)
            mLLDate = it.findViewById(R.id.mLLDate)
            mRvDate = it.findViewById(R.id.mRvDate)
            mLLComment = it.findViewById(R.id.mLLComment)
            mIvCIcon = it.findViewById(R.id.mIvCIcon)
            mTvCName = it.findViewById(R.id.mTvCName)
            mTvCTime = it.findViewById(R.id.mTvCTime)
            mTvComment = it.findViewById(R.id.mTvComment)
            mTabInside = it.findViewById(R.id.mTabInside)
            mAdapter.addHeaderView(it)
        }
        mLLComment?.setOnClickListener {
            val intent = Intent(this@ProductDetailActivity, CommentListActivity::class.java)
            intent.putExtra("id", id)
            intent.putExtra("type", 0)
            start(intent)
            overridePendingTransition(R.anim.activity_bottom_open, 0)
        }
    }

    // --------------- 获取详情 ---------------
    override fun getData(silence: Boolean)
    {
        val body = BaseModel(true)
        body.id = id
        mPresenter.getData(HttpDto(Constant.PRODUCT_DETAIL,
                                   body,
                                   silence).setType(HttpDto.GET).setFinish(true).setErrorTitle("获取玩家产品详情失败"))

        getComment()
    }

    var detail: ProductDetailVo? = null
    override fun bindDetail(data: ProductDetailVo)
    {
        detail = data
        if (data.productPicList.size > 0)
        {
            bindBanner(data.productPicList)
        }
        mTvTitle?.text = data.pdtName
        if (data.tags != null && data.tags.isNotEmpty())
        {
            mLLTag?.visibility = View.VISIBLE
            val strs =
                    data.tags.split("[;,/，、|]".toRegex())
                            .dropLastWhile { it.isEmpty() }
                            .toTypedArray()
            mTvTag1?.text = strs[0]
            if (strs.size > 1)
            {
                mTvTag2?.text = strs[1]
                if (strs.size > 2)
                {
                    mTvTag3?.text = strs[2]
                }
                else
                {
                    mTvTag3?.visibility = View.GONE
                }
            }
            else
            {
                mTvTag2?.visibility = View.GONE
                mTvTag3?.visibility = View.GONE
            }
        }
        mTvPrice?.text = MathTool.roundStr(data.salePrice, 2)
        mTvStart?.text = "${data.basePlace}出发"
        listData = arrayListOf()
        // 产品特色 FEATURES
        mealCardIndxList.add(listData.size)
        listData.add(ProductDetailItemVo(99, ""))
        data.productDetailList.forEach {
            listData.add(ProductDetailItemVo(99, ""))
            if (it.topCode == "FEATURES")
            {
                addItem(it.type, it.conUrl, it.videoUrl)
            }
        }
        // 详细行程
        mealCardIndxList.add(listData.size)
        listData.add(ProductDetailItemVo(99, ""))
        data.productTripList.forEach {
            listData.add(ProductDetailItemVo(it))
        }
        listData.add(ProductDetailItemVo(99, ""))
        // 费用说明 COST
        mealCardIndxList.add(listData.size)
        listData.add(ProductDetailItemVo(0, "费用说明"))
        data.productDetailList.forEach {
            if (it.topCode == "COST")
            {
                addItem(it.type, it.conUrl, it.videoUrl)
            }
        }
        // 预订须知 BOOK
        mealCardIndxList.add(listData.size)
        listData.add(ProductDetailItemVo(0, "预订须知"))
        data.productDetailList.forEach {
            if (it.topCode == "BOOK")
            {
                addItem(it.type, it.conUrl, it.videoUrl)
            }
        }
        listData.add(ProductDetailItemVo(100, ""))
        mAdapter.replaceData(listData)
        if (data.productDailyPriceList != null && data.productDailyPriceList.isNotEmpty())
        {
            mTvSure.isEnabled = true
            mLLDate?.visibility = View.VISIBLE
            mRvDate?.visibility = View.VISIBLE
            mLLDate?.setOnClickListener { choose() }
            mRvDate?.setOnClickListener { choose() }
            val dayAdapter = ProductDayAdapter(MathTool.roundStr(data.salePrice, 2))
            dayAdapter.setOnItemClickListener { adapter, view, position ->
                choose()
            }
            mRvDate?.addItemDecoration(DividerItemDecoration(DividerItemDecoration.HORIZONTAL_LIST,
                                                             R.color.transparent))
            mRvDate?.layoutManager = LinearLayoutManager(this@ProductDetailActivity, 0, false)
            mRvDate?.adapter = dayAdapter
            dayAdapter.replaceData(data.productDailyPriceList)
        }
    }

    private fun addItem(type: String?, info: String?, video: String?)
    { // 0:Tab  1:图片  2:文字  3:视频  4:行程
        if (type == "img")
        {
            listData.add(ProductDetailItemVo(1, info))
        }
        else if (type == "text")
        {
            listData.add(ProductDetailItemVo(2, info))
        }
        else if (type == "video")
        {
            val item = ProductDetailItemVo(3, info)
            item.videoUrl = video
            listData.add(item)
        }
    }

    // --------------- 获取评论信息 ---------------
    private fun getComment()
    {
        val body = BaseModel(true)
        body.pdtId = id
        mPresenter.getData(HttpDto(Constant.PRODUCT_COMMENT,
                                   body,
                                   true).setType(HttpDto.GET).setShowError(false))
    }

    override fun bindComment(data: CommentListVo)
    {
        if (data.list != null && data.list.size > 0)
        {
            mLLComment?.visibility = View.VISIBLE
            mIvCIcon?.let {
                GlideApp.with(it.context)
                        .load(data.list[0].headImg)
                        .centerCrop()
                        .into(it)
            }
            mTvCName?.text = DataTool.formatPhone(data.list[0].userName)
            mTvCTime?.text = Util.getTimeStr(data.list[0].createTime)
            mTvComment?.text = data.list[0].content
        }
    }

    // --------------- Banner ---------------
    var curVideoUrl = ""

    private fun bindBanner(list: List<ProductDetailVo.ProductPicListEntity>)
    {
        //参数设置
        if (list.isNotEmpty())
        {
            mLMBanners?.setAdapter(UrlImgAdapter(this@ProductDetailActivity), list)
            mLMBanners?.startImageTimerTask()
            mLMBanners?.setCanLoop(true)
        }
    }

    inner class UrlImgAdapter(private val mContext: Context) : LBaseAdapter<ProductDetailVo.ProductPicListEntity>
    {
        override fun getView(lBanners: LMBanners<*>, context: Context, position: Int, data: ProductDetailVo.ProductPicListEntity): View
        {
            val view =
                    LayoutInflater.from(mContext)
                            .inflate(R.layout.item_banner, null)
            val play = view.findViewById(R.id.mPlayImageView) as PlayImageView
            if (data.type == "VIDEO")
            {
                play.setData("", data.url) { img, video ->
                    if (curVideoUrl == video)
                    {
                    }
                    else
                    {
                        if (RegTool.isEmpty(curVideoUrl))
                        {
                            mJzvdStd.setUp(video, "")
                        }
                        else
                        {
                            mJzvdStd.changeUrl(video, "", 0L)
                        }

                        if (RegTool.isEmpty(img))
                        {
                            try
                            {
                                Glide.with(this@ProductDetailActivity)
                                        .setDefaultRequestOptions(RequestOptions().frame(0).centerCrop().error(
                                                ColorDrawable(Color.BLACK)).placeholder(
                                                ColorDrawable(Color.BLACK)))
                                        .load(video)
                                        .into(mJzvdStd.thumbImageView)
                            }
                            catch (e: Exception)
                            {
                                e.printStackTrace()
                            }
                        }
                        else
                        {
                            GlideTool.loadImg(mJzvdStd.thumbImageView,
                                              img,
                                              ColorDrawable(Color.BLACK))
                        }
                        curVideoUrl = video
                    }
                    mRLVideo.visibility = View.VISIBLE
                    mIvVideoClose.visibility = View.VISIBLE
                    mJzvdStd.startVideo()
                }
            }
            else
            {
                play.setData(data.url, "", null)
            }
            return view
        }
    }

    override fun onResume()
    {
        if (mLMBanners != null && mLMBanners?.itemCount!! > 1)
        {
            mLMBanners?.startImageTimerTask()
        }
        super.onResume()
    }

    override fun onDestroy()
    {
        if (mLMBanners != null)
        {
            mLMBanners?.clearImageTimerTask()
        }
        super.onDestroy()
    }

    // --------------- TabLayout ---------------
    private val pointText = arrayOf("产品特色", "详细行程", "费用说明", "预订须知")

    private fun initTab()
    {
        pointText.forEach {
            addAimingPoint(mTabInside!!, it)
            addAimingPoint(mTabOutside, it)
        }
        mTabInside?.setOnTabSelectedListener(this)
        mTabOutside.setOnTabSelectedListener(this)
        TabLayoutAddOnClickHelper.AddOnClick(mTabInside!!, tabOnClickListener)
        TabLayoutAddOnClickHelper.AddOnClick(mTabOutside, tabOnClickListener)
    }

    private val tabOnClickListener = object : View.OnTouchListener
    {
        override fun onTouch(v: View, event: MotionEvent): Boolean
        {
            if (event.action == MotionEvent.ACTION_UP)
            {
                val pos = v.tag as Int
                mTabOutside.getTabAt(pos)!!.select()
                mTabInside?.getTabAt(pos)!!.select()
                if (pos != 0)
                {
                    mTabOutside.visibility = View.VISIBLE
                }
                else
                {
                    mTabOutside.visibility = View.GONE
                }
                moveRecycleViewToPosition(mealCardIndxList[pos])
                return true
            }
            else
            {
                return false
            }
        }
    }

    fun addAimingPoint(tabLayout: TabLayout, text: String)
    {
        tabLayout.addTab(tabLayout.newTab().setText(text))
    }

    override fun onTabSelected(tab: TabLayout.Tab)
    {
        /**导航控制*/
        if (layoutManager.findFirstVisibleItemPosition() >= 1)
        {
            mTabOutside.visibility = View.VISIBLE
        }
        else
        {
            mTabOutside.visibility = View.GONE
        }
    }

    override fun onTabReselected(p0: TabLayout.Tab?)
    {
    }

    override fun onTabUnselected(tab: TabLayout.Tab)
    {
    }

    // --------------- RecyclerView ---------------
    private val mAdapter = ProductDetailAdapter(arrayListOf())
    private val layoutManager = FullyLinearLayoutManager(this@ProductDetailActivity)
    private var isFormTabScroll = false
    private var mealCardIndxList: ArrayList<Int> = arrayListOf()
    private var listData: ArrayList<ProductDetailItemVo> = arrayListOf()
    private fun initRecyclerView()
    {
        mRecyclerView.addItemDecoration(DividerItemDecoration(this@ProductDetailActivity,
                                                              DividerItemDecoration.VERTICAL_LIST,
                                                              R.color.transparent,
                                                              0,
                                                              true))
        mRecyclerView.layoutManager = layoutManager
        mRecyclerView.adapter = mAdapter

        mRecyclerView.addOnScrollListener(object : RecyclerView.OnScrollListener()
                                          {
                                              override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int)
                                              {
                                                  super.onScrolled(recyclerView, dx, dy)
                                                  //遍历锚点
                                                  //不捕获自动滚动，非用户触摸产生的滑动
                                                  if (isFormTabScroll)
                                                  {
                                                      return
                                                  }
                                                  //监听滑动距离，改变tab选中位置
                                                  val position =
                                                          layoutManager.findFirstVisibleItemPosition()
                                                  /**导航控制*/
                                                  if (position >= 1)
                                                  {
                                                      mTabOutside.visibility = View.VISIBLE
                                                  }
                                                  else
                                                  {
                                                      mTabOutside.visibility = View.GONE
                                                  }
                                                  val headCount = mAdapter.headerLayoutCount
                                                  val realPosition = position - headCount
                                                  //因为有1个header所以>=-1
                                                  if (realPosition >= -1 && realPosition < mAdapter.data.size)
                                                  {
                                                      if (mealCardIndxList.size == mTabOutside.tabCount)
                                                      { //防止下标越界异常
                                                          //判断当前item所处类定位tab
                                                          for (i in mealCardIndxList.indices)
                                                          {
                                                              if (i == 0)
                                                              {
                                                                  if (realPosition >= -1 && realPosition < mealCardIndxList[1])
                                                                  {
                                                                      if (mTabOutside.selectedTabPosition != 0)
                                                                      {
                                                                          mTabOutside.getTabAt(i)!!.select()
                                                                          mTabInside?.getTabAt(i)!!.select()
                                                                          break
                                                                      }
                                                                  }
                                                              }
                                                              else if (i < 3)
                                                              {
                                                                  if (realPosition >= mealCardIndxList[i] && realPosition < mealCardIndxList[i + 1])
                                                                  {
                                                                      if (mTabOutside.selectedTabPosition != i)
                                                                      {
                                                                          mTabOutside.getTabAt(i)!!.select()
                                                                          mTabInside?.getTabAt(i)!!.select()
                                                                          break;
                                                                      }
                                                                  }
                                                              }
                                                              //可能会有i==0的情况下属于如下情况 所以不加else if
                                                              if (i == mealCardIndxList.size - 1)
                                                              {
                                                                  if (realPosition >= mealCardIndxList.get(
                                                                              i))
                                                                  {
                                                                      if (mTabOutside.selectedTabPosition != i)
                                                                      {
                                                                          mTabOutside.getTabAt(i)!!.select()
                                                                          mTabInside?.getTabAt(i)!!.select()
                                                                      }
                                                                  }
                                                              }
                                                          }
                                                      }
                                                  }
                                              }

                                              override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int)
                                              {
                                                  super.onScrollStateChanged(recyclerView, newState)

                                                  when (newState)
                                                  {
                                                      RecyclerView.SCROLL_STATE_DRAGGING ->
                                                      {
                                                          isFormTabScroll = false
                                                      }
                                                      RecyclerView.SCROLL_STATE_IDLE     ->
                                                      {
                                                          //                                                          if (flowDetailActivity != null && !flowDetailActivity.isCloseNps())
                                                          //                                                          {
                                                          //                                                              UIUtils.postDelayRunnable(Runnable {
                                                          //                                                                  if (!flowDetailActivity.isShowNps())
                                                          //                                                                  {
                                                          //                                                                      flowDetailActivity.showNPS()
                                                          //                                                                  }
                                                          //                                                              }, 100)
                                                          //                                                          }
                                                      }
                                                      else                               ->
                                                      {
                                                      }
                                                  }
                                              }
                                          })

        mRecyclerView.viewTreeObserver.addOnScrollChangedListener {
            //将改item滑动到顶部
            if (needMoveToTop)
            {
                needMoveToTop = false
                //获取要置顶的项在当前屏幕的位置，mIndex是记录的要置顶项在RecyclerView中的位置
                val n = mIndex - layoutManager.findFirstVisibleItemPosition()
                if (0 <= n && n < mRecyclerView.childCount)
                {
                    //获取要置顶的项顶部离RecyclerView顶部的距离
                    val top =
                            mRecyclerView.getChildAt(n)
                                    .top
                    //最后的移动
                    mRecyclerView.scrollBy(0, top)
                }
            }
        }
    }

    var mIndex = -1
    var needMoveToTop = true
    fun moveRecycleViewToPosition(pos: Int)
    {
        var n = 0
        if (pos != 0)
        {
            n = pos + 1
        }
        isFormTabScroll = true
        //先从RecyclerView的LayoutManager中获取第一项和最后一项的Position
        val firstItem = layoutManager.findFirstVisibleItemPosition()
        val lastItem = layoutManager.findLastVisibleItemPosition()
        //然后区分情况
        if (n < firstItem)
        {
            //当要置顶的项在当前显示的第一个项的前面时
            mRecyclerView.scrollToPosition(n)
            if (n != 0)
            {
                mIndex = n
                needMoveToTop = true
            }
        }
        else if (n <= lastItem)
        {
            //当要置顶的项已经在屏幕上显示时
            val top =
                    mRecyclerView.getChildAt(n - firstItem)
                            .top
            mRecyclerView.scrollBy(0, top)
        }
        else
        {
            //当要置顶的项在当前显示的最后一项的后面时
            mRecyclerView.scrollToPosition(n)
            //这里这个变量是用在RecyclerView滚动监听里面的
            mIndex = n
            needMoveToTop = true
        }
    }

    override fun collectSuccess()
    {
        mTvCollect.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.i_star_yes, 0, 0)
    }

    // --------------- 分享 ----------------
    private var shareDialog: Dialog? = null
    private var dImage: ImageView? = null
    private fun showShareDialog(bitmap: Bitmap)
    {
        shareDialog
                ?: let {
                    shareDialog = Dialog(this@ProductDetailActivity, R.style.dialog)
                    shareDialog?.setContentView(R.layout.dialog_share)
                    shareDialog?.setCanceledOnTouchOutside(false)
                    val display = window.windowManager.defaultDisplay
                    val layoutParams: WindowManager.LayoutParams = shareDialog?.window!!.attributes
                    layoutParams.width = (display.width * 0.8f).toInt()
                    layoutParams.height = (display.height * 0.9f).toInt()
                    shareDialog?.window!!.attributes = layoutParams
                    dImage = shareDialog?.findViewById(R.id.dImage)

                    shareDialog?.findViewById<TextView>(R.id.dTvSure)
                            ?.setOnClickListener {
                                showDialog()
                                Observable.just(bitmap)
                                        .subscribeOn(Schedulers.io())
                                        .map { v ->
                                            Uri.parse(MediaStore.Images.Media.insertImage(
                                                    contentResolver,
                                                    v,
                                                    null,
                                                    null))
                                        }
                                        .observeOn(AndroidSchedulers.mainThread())
                                        .subscribe({ uri ->
                                                       disDialog()
                                                       val shareIntent = Intent()
                                                       shareIntent.action = Intent.ACTION_SEND
                                                       shareIntent.putExtra(Intent.EXTRA_STREAM,
                                                                            uri)
                                                       shareIntent.type = "image/*"
                                                       start(Intent.createChooser(shareIntent,
                                                                                  "分享到"))
                                                       shareDialog?.dismiss()
                                                   }) { t ->
                                            t.printStackTrace()
                                            disDialog()
                                            RxToast.error("分享失败")
                                        }
                            }
                    shareDialog?.findViewById<TextView>(R.id.dTvCancel)
                            ?.setOnClickListener {
                                bitmap.recycle()
                                shareDialog?.dismiss()
                            }
                }
        dImage?.setImageBitmap(bitmap)
        shareDialog?.show()
    }
}